//
//  WBStatusPictureView.swift
//  Weibo
//
//  Created by kobe on 2016/12/26.
//  Copyright © 2016年 kobe. All rights reserved.
//

import UIKit

class WBStatusPictureView: UIView {
    
    var viewModel:WBStatusViewModel? {
        didSet {
            calcViewSize()
        }
    }
    
    fileprivate func calcViewSize() {
        
        //处理宽度
        // 1>单图 根据配图视图的大小 修改subview[0]的宽高
        if viewModel?.picURLs?.count == 1 {
            
            let viewSize = viewModel?.pictureSize ?? CGSize()
            // a.获取第0个图像
            let v = subviews[0]
            v.frame = CGRect(x: 0, y: WBStatusPictureViewOutterMargin, width: viewSize.width, height: viewSize.height - WBStatusPictureViewOutterMargin)
            
        } else {
             // 2> 多图 回复subview[0]的宽高
            let v = subviews[0]
            v.frame = CGRect(x: 0, y: WBStatusPictureViewOutterMargin, width: WBStatusPictureItemWidth, height: WBStatusPictureItemWidth)
            
        }
        
       
        
        
        heighCons.constant = viewModel?.pictureSize.height ?? 0
    }
    
    var urls:[WBStatusPicture]? {
        didSet {
            // 隐藏所有的图片
            for v in subviews {
                v.isHidden = true
            }
            
            //遍历urls数组
            var index = 0
            for url in urls ?? [] {
                let iv = subviews[index] as! UIImageView
                
                if index == 1 && urls?.count == 4 {
                    index += 1
                }
                
                
                iv.cz_setImage(urlStr: url.thumbnail_pic, placeholderImage: nil)
                
                // 显示图像
                iv.isHidden = false
                
                
                index += 1
            }
        }
    }

    @IBOutlet weak var heighCons:NSLayoutConstraint!
    
    override func awakeFromNib() {
        setupUI()
    }

}

extension WBStatusPictureView {
    
    fileprivate func setupUI() {
        
        backgroundColor = superview?.backgroundColor
        
        clipsToBounds = true
        
        let rect = CGRect(x: 0, y: WBStatusPictureViewOutterMargin, width: WBStatusPictureItemWidth, height: WBStatusPictureItemWidth)
        let count = 3
        for i in 0..<count * count {
            let iv = UIImageView()
            iv.contentMode = .scaleAspectFill
            iv.clipsToBounds = true
            
            //行
            let row = CGFloat(i / count)
            
            let col = CGFloat(i % count)
            
            let xOffset = col * (WBStatusPictureItemWidth + WBStatusPictureViewinnerMargin)
            let yOffset = row * (WBStatusPictureItemWidth + WBStatusPictureViewinnerMargin)
            
            
            
            
            iv.frame = rect.offsetBy(dx: xOffset, dy: yOffset)
            addSubview(iv)
        }
    }
    
}
